/**
 * jquery.ztree 组件封装
 */

// 根路径
var ROOT_PATH = "ztree/"
document.write("<link rel='stylesheet' href='" + ROOT_PATH + "css/demo.css' type='text/css'/>");
document.write("<link rel='stylesheet' href='" + ROOT_PATH + "css/zTreeStyle/zTreeStyle.css' type='text/css'/>");

document.write("<script src='" + ROOT_PATH + "js/jquery.ztree.all.min.js'></script>");
(function ($) {

    // 配置默认参数
    var default_options = {
        method: "get",
        checkEnable: false,
        simpleDataEnable:true
    };

    /**
     * 渲染ztree初始化
     * @param options
     */
    $.fn.ztreeInit = function (options) {

        if (!options) {
            throw "url is not empty";
        }

        // 设置默认值
        $.each(default_options, function (key, value) {
            if (!options[key]) {
                options[key] = value;
            }
        });

        var _this = $(this);
        _this.addClass("ztree");
        var setting = {
            data: {
                simpleData: {
                    enable: options.simpleDataEnable
                }
            },
            check: {
                enable: options.checkEnable
            }
        };

        if(options.callback){
            setting.callback = options.callback;
        }

        var zNodes = [];

        $.ajax({
            url: options.url,
            type: options.method,
            async: false,
            success: function (data) {
                if (options.success) {
                    options.success(data);
                }
                zNodes = data;
            }
        });

        $.fn.zTree.init(_this, setting, zNodes);
    }

    /**
     * 获取方法
     * @param methodName
     * @returns {*}
     */
    $.fn.ztreeGet = function (methodName, value) {
        var treeObj = $.fn.zTree.getZTreeObj($(this).attr("id"));
        if (!methodName) {
            throw "method's name is empty"
        }
        if (methodName == "selectedNodes") {
            return treeObj.getSelectedNodes();
        }
        if (methodName == "getCheckedNodes") {
            if (typeof value == "undefined") {
                value = true;
            }
            return treeObj.getCheckedNodes(value);
        }
        throw "not find method";
    }
})(jQuery);